/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.repository.metric.clickhouse;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.MetricEntity;
import com.alibaba.csp.sentinel.dashboard.repository.metric.MetricsRepository;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.clickhouse.client.internal.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

/**
 * Caches metrics data in a period of time in clickhouse.
 *
 * @author wangjainying
 */
@Component
public class ClickhouseMetricsRepository implements MetricsRepository<MetricEntity> {

    @Autowired
    private TSecondsMetricDao tSecondsMetricDao;

    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    @Override
    public void save(MetricEntity entity) {
        if (entity == null || StringUtil.isBlank(entity.getApp())) {
            return;
        }
        readWriteLock.writeLock().lock();
        try {
            saveAll(Arrays.asList(entity));
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    @Override
    public void saveAll(Iterable<MetricEntity> metrics) {
        if (metrics == null) {
            return;
        }
        readWriteLock.writeLock().lock();
        try {
            tSecondsMetricDao.insertBatchJson(JsonParser.parseString(JSONObject.toJSONString(toTSecondsMetricList(metrics))));
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    private List<TSecondsMetric> toTSecondsMetricList(Iterable<MetricEntity> metrics) {
        List<TSecondsMetric> tSecondsMetrics = new ArrayList<>();
        metrics.forEach(m->{
            TSecondsMetric tSecondsMetric = new TSecondsMetric();
            tSecondsMetric.setApp(m.getApp());
            tSecondsMetric.setResource(m.getResource());
            tSecondsMetric.setTimestamp(m.getTimestamp());
            tSecondsMetric.setPassQps(m.getPassQps().intValue());
            tSecondsMetric.setBlockQps(m.getBlockQps().intValue());
            tSecondsMetric.setSuccessQps(m.getSuccessQps().intValue());
            tSecondsMetric.setExceptionQps(m.getExceptionQps().intValue());
            if (m.getSuccessQps() != 0) {
                tSecondsMetric.setRt(((int) (m.getRt() / m.getSuccessQps())));
            } else {
                tSecondsMetric.setRt((0));
            }
            tSecondsMetric.setCount(m.getCount());
            tSecondsMetrics.add(tSecondsMetric);
        });
        return tSecondsMetrics;
    }

    private List<MetricEntity> toMetricEntityList(Iterable<TSecondsMetric> tSecondsMetrics) {
        List<MetricEntity> entities = new ArrayList<>();
        tSecondsMetrics.forEach(m->{
            MetricEntity metricEntity = new MetricEntity();
            metricEntity.setApp(m.getApp());
            metricEntity.setResource(m.getResource());
            metricEntity.setTimestamp(m.getTimestamp());
            metricEntity.setPassQps(m.getPassQps().longValue());
            metricEntity.setBlockQps(m.getBlockQps().longValue());
            metricEntity.setSuccessQps(m.getSuccessQps().longValue());
            metricEntity.setExceptionQps(m.getExceptionQps().longValue());
            metricEntity.setRt(((m.getRt() * m.getSuccessQps())));
            metricEntity.setCount(m.getCount());
            metricEntity.setCount(m.getCount());
            metricEntity.setGmtCreate(m.getGmtCreate());
            metricEntity.setGmtModified(m.getGmtCreate());
            entities.add(metricEntity);
        });
        return entities;
    }

    @Override
    public List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime) {
        List<TSecondsMetric> tSecondsMetrics = tSecondsMetricDao.selectByAppAndResourceBetween(app, resource, new Date(startTime), new Date(endTime));
        return toMetricEntityList(tSecondsMetrics);
    }

    @Override
    public List<String> listResourcesOfApp(String app) {
        List<String> results = new ArrayList<>();
        if (StringUtil.isBlank(app)) {
            return results;
        }
        final long minTimeMs = System.currentTimeMillis() - 1000 * 60;
        Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32);

        List<TSecondsMetric> tSecondsMetrics = tSecondsMetricDao.selectByAppAndResourceBetween(app, null, new Date(minTimeMs), new Date());
        List<MetricEntity> metricEntityList = toMetricEntityList(tSecondsMetrics);

        for (MetricEntity metricEntity : metricEntityList) {
            MetricEntity newEntity = metricEntity;
            if (resourceCount.containsKey(newEntity.getResource())) {
                MetricEntity oldEntity = resourceCount.get(newEntity.getResource());
                oldEntity.addPassQps(newEntity.getPassQps());
                oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps());
                oldEntity.addBlockQps(newEntity.getBlockQps());
                oldEntity.addExceptionQps(newEntity.getExceptionQps());
                oldEntity.addCount(1);
            } else {
                resourceCount.put(newEntity.getResource(), MetricEntity.copyOf(newEntity));
            }
        }
        // Order by last minute b_qps DESC.
        return resourceCount.entrySet()
                .stream()
                .sorted((o1, o2) -> {
                    MetricEntity e1 = o1.getValue();
                    MetricEntity e2 = o2.getValue();
                    int t = e2.getBlockQps().compareTo(e1.getBlockQps());
                    if (t != 0) {
                        return t;
                    }
                    return e2.getPassQps().compareTo(e1.getPassQps());
                })
                .map(Entry::getKey)
                .collect(Collectors.toList());
    }
}
